class WelcomeController < ApplicationController
  before_filter :login_required

  def index
    @user = session['user']
    id = @user.id

    # inbox
    @inbox = Task.find(:all, :conditions=>"task_id=0 and done=0 and user_id=#{id} and (project_id=0 or title='')")

    
    # I had some tasks that had a project different from their parent task....
    
    #sql = ActiveRecord::Base.connection();
	  #sql.execute "update tasks A set project_id=(select * from (select project_id from tasks T where T.id=task_id) tmp) where task_id!=0";

    #@lost = Task.find_by_sql("select * from tasks where task_id!=0 and project_id!=(select project_id from tasks T where T.id=tasks.task_id)")
    

    # invitations
    @invit = Invitation.find_all_by_email(@user.email)
    if(@invit != [] and @user.projects.size==0) # accept automatically
      @user.accept_invitation(@invit)
      @invit = []
      flash[:notice] = "You've just joined the projects you've been invited to. Create a new task now by clicking on tasks, in the menu above."
    end

    # view
    @projects        = @user.active_projects
    pids = @projects.collect {|p| p.id}.join(',')

    cond  = "done='0' and state='next' and user_id='#{id}' and (project_id!=NULL or title!='')"
    cond += " and project_id in (#{pids})" if pids != ''
    
    #@important_tasks = Task.find(:all, :conditions=>cond, :order=>"priority,`order`", :limit=>10)
    
    cond = "done='1' and user_id!=#{id}"
    cond += " and project_id in (#{pids})" if pids != ''
    @tasksdone1      = Task.find(:all, :conditions=>cond+" and done_on > CURRENT_DATE() - INTERVAL 1 DAY", :order=>'done_on desc')
    @tasksdone2      = Task.find(:all, :conditions=>cond+" and done_on between (CURRENT_DATE() - INTERVAL 8 DAY) and (CURRENT_DATE() - INTERVAL 1 DAY)", :order=>'done_on desc')

    cond = "done='0' and user_id='#{id}'"
    cond += " and duedate<=CURRENT_DATE()+ INTERVAL 8 DAY"
    cond += " and project_id in (#{pids})" if pids != ''

    @deadlines= Task.find(:all, :conditions=>cond, :order=>"duedate,priority,`order`")
    
    calcond = "user_id=#{id}"
    calcond = "project_id in (#{pids})" if pids != ''
    calcond += " and date <= CURRENT_DATE() + INTERVAL 1 MONTH"
    calcond += " and date >= CURRENT_DATE() - INTERVAL 3 DAY"
    @calendar = Calendar.find(:all, :conditions=>calcond, :order=>"date")
  end

end

